package com.cctc.juc.demo.Athread.Bcreate.CCallableAndFutureTask;

import java.util.concurrent.*;

public class CallableAndFutureTaskDemo02 {
    public static class TaskCallable implements Callable<Long> {
        @Override
        public Long call() throws Exception {
            long startTime = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + " 线程，FutureTask 异步任务运行开始...");

            TimeUnit.SECONDS.sleep(6);

            long userTime = System.currentTimeMillis() - startTime;
            System.out.println(Thread.currentThread().getName() + " 线程，FutureTask 异步任务运行结束...");
            return userTime;
        }
    }

    public static void main(String[] args) {
        TaskCallable callable = new TaskCallable();
        FutureTask<Long> futureTask = new FutureTask<>(callable);
        /**
         * 使用线程池中的线程，执行 FutureTask 异步任务。
         * - 方法调用链：Thread.run() -> FutureTask.run() -> Callable.run()。
         */
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(futureTask);

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(Thread.currentThread().getName() + " 线程，等待 FutureTask 异步任务运行完毕...");
        System.out.println(Thread.currentThread().getName() + " 线程，做一点自己的事情...");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
            System.out.println(Thread.currentThread().getName() + " 线程，获取 FutureTask 异步任务执行结果 -> 线程运行时间：" + futureTask.get() + " ms.");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } finally {
            executorService.shutdown();
        }

        System.out.println(Thread.currentThread().getName() + " 线程运行结束.");
    }
}
